package demo15;

import java.util.HashSet;
import java.util.Set;

public class SetDemo {
    public static void main(String[] args) {
        // 创建一个Set对象，这里使用HashSet实现
        Set<String> books = new HashSet<>();

        // 添加元素到Set
        books.add("1984");
        books.add("To Kill a Mockingbird");
        books.add("The Great Gatsby");

        // 尝试添加重复元素
        boolean addedDuplicate = books.add("1984");
        System.out.println("Was '1984' added again? " + addedDuplicate);

        // 打印Set中的所有元素
        System.out.println("Initial Set: " + books);

        // 检查Set是否包含某个元素
        boolean containsBook = books.contains("1984");
        System.out.println("Does the set contain '1984'? " + containsBook);

        // 删除Set中的元素
        books.remove("The Great Gatsby");
        System.out.println("Set after removal: " + books);

        // 获取Set的大小
        int size = books.size();
        System.out.println("Size of the set: " + size);

        // 遍历Set中的元素
        System.out.println("Iterating through the set:");
        for (String book : books) {
            System.out.println(book);
        }
    }
}